package com.clip.util.mail;

import java.util.LinkedHashMap;
import java.util.Map;

import net.sf.jml.MsnContact;
import net.sf.jml.MsnMessenger;
import net.sf.jml.MsnProtocol;
import net.sf.jml.MsnUserStatus;
import net.sf.jml.event.MsnAdapter;
import net.sf.jml.impl.MsnMessengerFactory;

public class MsnBasicMessenger {
	public static Map<String,Object> importMsnMessenger(String name,String pwd){
		MsnMessenger messenger = MsnMessengerFactory.createMsnMessenger(name,pwd);

        //MsnMessenger support all protocols by default
        messenger.setSupportedProtocol(new MsnProtocol[] { MsnProtocol.MSNP8 });

        //default init status is online, 
        messenger.getOwner().setInitStatus(MsnUserStatus.HIDE);
        //log incoming message
//        messenger.setLogIncoming(true);
        messenger.setSupportedProtocol(new MsnProtocol[]{MsnProtocol.MSNP12});
        
        //log outgoing message
//        messenger.setLogOutgoing(true);

        messenger.addListener(new MsnAdapter(){
        	
			@Override
			public void exceptionCaught(MsnMessenger arg0, Throwable arg1) {
				arg0.getOwner().setProcessStatus(arg1.getMessage()==null ? 2 : 1);
				System.out.println(arg1.getMessage());
				super.exceptionCaught(arg0, arg1);
			}

			@Override
			public void contactListInitCompleted(MsnMessenger arg0) {
				super.contactListInitCompleted(arg0);
			}

			@Override
			public void contactListSyncCompleted(MsnMessenger arg0) {
				arg0.getOwner().setProcessStatus(3);
				super.contactListSyncCompleted(arg0);
			}
        } );
        messenger.login();
        boolean login = true;
        boolean load = true;
        MsnContact[] cons  = {};
        Map<String,Object> map = new LinkedHashMap<String, Object>();
        while(login){
        	int status = messenger.getOwner().getProcessStatus();
        	if(status>0){
        		login = false;
        		if(status==1){
        			map.put("flag", 0);
        		}else{
        			map.put("flag", 1);
        			while(load){
        				status = messenger.getOwner().getProcessStatus();
            			if(status==3){
            				load = false;
            				cons = messenger.getContactList().getContacts();
            			}
            		}
        		}
        	}
        }
        map.put("con", cons);
        map.put("messenger", messenger);
		return map;
	}
}
